package com.qf.blog.system.interceptor;

import com.qf.blog.core.exception.TokenException;
import com.qf.blog.system.dto.UserToken;
import com.qf.blog.system.service.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1.获取token
        String token = request.getHeader("token");

        // 2.校验token合法性
        if (ObjectUtils.isEmpty(token)) {
            throw new TokenException(201, "token为空");
        }
        UserToken userToken = tokenService.getToken(token);
        if (userToken == null) {
            throw new TokenException(201, "token有误");
        }

        // 放行
        return true;
    }
}
